package com.dsunsoft.rtu.core.base;

import com.dsunsoft.rtu.common.entity.BaseEntity;
import com.dsunsoft.rtu.common.entity.BaseQuery;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * BaseServiceImpl
 *
 * @param <TMapper> BaseMapper
 * @param <E>       BaseEntity
 * @param <Q>       BaseQuery
 * @author ygm
 */
public class BaseServiceImpl<TMapper extends BaseMapper<E, Q>, E extends BaseEntity, Q extends BaseQuery>
        implements BaseService<E, Q> {

    /**
     * 持久层对象
     */
    @Autowired
    protected TMapper mapper;

    /**
     * 通过id获取数据
     *
     * @param id 主键id
     * @return 对象
     */
    @Override
    public E getById(String id) {
        return mapper.selectById(id);
    }

    /**
     * 获取列表数据
     *
     * @param query 查询对象
     * @return list
     */
    @Override
    public List<E> queryList(Q query) {
        return mapper.selectList(query);
    }

    /**
     * 分页获取列表数据
     *
     * @param query 查询对象
     * @return 分页数据
     */
    @Override
    public PageInfo<E> queryPage(Q query) {
        Page<E> page = PageHelper.startPage(query.getPageIndex(), query.getPageSize());
        if (StringUtils.isNotBlank(query.getOrderBy())) {
            page.setUnsafeOrderBy(query.getOrderBy());
        }
        List<E> list = mapper.selectList(query);
        return new PageInfo<>(list);
    }

    /**
     * 新增
     *
     * @param entity 新增对象
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean insert(E entity) {
        return mapper.insert(entity) > 0;
    }

    /**
     * 修改
     *
     * @param entity 修改对象
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(E entity) {
        return mapper.update(entity) > 0;
    }

    /**
     * 通过id删除
     *
     * @param id 主键id
     * @return boolean
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteById(String id) {
        return mapper.deleteById(id) > 0;
    }
}
